#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/epoll.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
 
#define MAX_EVENT_NUMBER 1024
#define BUFFER_SIZE 10
 
// 将文件描述符设置成非阻塞
int setNonBlocking(int fd){
    int old_opt = fcntl(fd, F_GETFD);
    int new_opt = old_opt | O_NONBLOCK;
    fcntl(fd, F_SETFD,new_opt);
    return old_opt;
}
 
/**
 将文件描述符fd上的EPOLLIN注册到epollfd指示的epoll内核事件中，参数enable_ET指定是否对fd启用ET模式
 */
void addfd(int epollfd, int fd,bool enable_et){
    epoll_event event;
    event.data.fd = fd;
    event.events = EPOLLIN;
    if (enable_et) {
        event.events |= EPOLLET;
    }
    epoll_ctl(epollfd, EPOLL_CTL_ADD,fd, &event);
    setNonBlocking(fd);
}
 
void lt(epoll_event* events, int number, int epollfd,int listenfd){
    char buf[BUFFER_SIZE];
    for(int i = 0;i < number;i++){
        int sockfd = events[i].data.fd;
        if (sockfd == listenfd) {
            struct sockaddr_in client_address;
            socklen_t client_addrlength = sizeof(client_address);
            int connfd = accept(listenfd, (struct sockaddr*) &client_address, &client_addrlength);
 	    addfd(epollfd, connfd, false); // 对connfd禁用ET模式
        }else if(events[i].events & EPOLLIN){
            // 读取缓冲区未读取的数据
            printf("event trgger once\n");
            memset(buf, '\0', BUFFER_SIZE);
            int ret = recv(sockfd, buf, BUFFER_SIZE-1, 0);
            if (ret <= 0) {
                close(sockfd);
            }
            printf("get %d bytes of content: %s\n",ret, buf);
        }else{
            printf("something else happened\n");
        }
    }
    
}
 
 
void et(epoll_event* events,int number,int epollfd, int listenfd){
    char buf[BUFFER_SIZE];
    for(int i = 0;i < number;i++){
        int sockfd = events[i].data.fd;
        if (sockfd == listenfd) {
            struct sockaddr_in client_address;
            socklen_t client_addrlength = sizeof(client_address);
            int connfd = accept(listenfd, (struct sockaddr*) &client_address, &client_addrlength);
            addfd(epollfd, connfd, true); // 对connfd 开启ET模式
            
        }else if(events[i].events & EPOLLIN){
            // 下面的代码不会被重复触发,所以循环读取数据,确保把socket读缓冲的所有数据读出
            printf("event trigger once\n");
	    while(1){
		memset(buf,'\0',BUFFER_SIZE);
		int ret = recv(sockfd, buf, BUFFER_SIZE-1,0);
		if(ret < 0){
		    if((errno == EAGAIN) || (errno == EWOULDBLOCK)){
		        printf("read later\n");
			break;
		    }
		    close(sockfd);
		    break;
		}else if(ret == 0){// ret < 0
		    close(sockfd);
		    printf("client disconnected\n");
		    break;
		}else{
		    printf("get %d bytes of content: %s\n",ret,buf);
		    break;
		}
	    }// while
	}else{
	    printf("something else happened\n");
	}// sockfd == listenfd
    }
}
 
int main(int argc, const char * argv[]) {
    
    if (argc <= 2) {
        printf("usage: %s ip_address port_number\n", basename(argv[0]));
        return 1;
    }
    const char* ip = argv[1];
    int port = atoi(argv[2]);
    
    int ret = 0;
    struct sockaddr_in address;
    bzero(&address, sizeof(address));
    address.sin_family = AF_INET;
    inet_pton(AF_INET, ip, &address.sin_addr);
    address.sin_port = htons(port);
    
    int socket_fd = socket(PF_INET, SOCK_STREAM, 0);
    if ( socket_fd == -1 ){
        perror("create socket error");
        exit(1);
    }
    ret = bind(socket_fd, (struct sockaddr*)& address, sizeof(address));
    if(ret == -1 ) {
        perror("bind error");
        exit(1);
    }
 
    ret = listen(socket_fd, 5);
    if ( ret == -1 ){
        perror("listen error");
        exit(1);
    }
    
    epoll_event events[MAX_EVENT_NUMBER];
    int epollfd = epoll_create(5);
    if (epollfd == -1) {
        perror("epoll create error");
        exit(1);
    }
    
    addfd(epollfd, socket_fd, true);
    
    while (1) {
        int ret = epoll_wait(epollfd, events, MAX_EVENT_NUMBER, -1);
        if(ret < 0){
            printf("epoll failure\n");
            break;
        }
        et(events, ret, epollfd, socket_fd);
    	printf("wait...\n");
    }
    close(socket_fd);
    return 0;
}